<template>
  <div class="categories-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>分类管理</h2>
        <p>管理博客文章分类，包括创建、编辑、删除等操作</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建分类
        </el-button>
      </div>
    </div>
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-card>
        <el-form :inline="true" @submit.prevent>
          <el-form-item label="搜索分类名">
            <el-input
              v-model="searchName"
              placeholder="搜索分类名"
              clearable
              @keyup.enter="fetchCategories"
              style="width: 220px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchCategories">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <!-- 分类列表 -->
    <div class="categories-list">
      <el-card>
        <el-table
          v-loading="loading"
          :data="categories"
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          
          <el-table-column prop="name" label="分类名称" min-width="150" />
          
          <el-table-column prop="slug" label="别名" width="120" />
          
          <el-table-column prop="description" label="描述" min-width="200" />
          
          <el-table-column prop="article_count" label="文章数量" width="100" />
          
          <el-table-column prop="created_at" label="创建时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="editCategory(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteCategory(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 创建/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '新建分类'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入分类名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="别名" prop="slug">
          <el-input
            v-model="form.slug"
            placeholder="请输入别名（英文）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCategory" :loading="saving">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { categoryApi } from '@/api/admin'

// 搜索关键字
const searchName = ref('')
// 分类列表
const categories = ref([])
const loading = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)

// 表单引用
const formRef = ref(null)
// 分类id
const editingId = ref(null)

// 表单数据
const form = ref({
  name: '',
  slug: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入别名', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '别名只能包含小写字母、数字和连字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    const params = {}
    if (searchName.value) params.search = searchName.value
    const response = await categoryApi.getCategories(params)
    categories.value = response.data || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  form.value = {
    name: '',
    slug: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑分类
const editCategory = (category) => {
  isEdit.value = true
  editingId.value = category.id
  form.value = {
    name: category.name,
    slug: category.slug,
    description: category.description || ''
  }
  dialogVisible.value = true
}

// 保存分类
const saveCategory = async (id) => {
  try {
    await formRef.value.validate()
    saving.value = true
    
    if (isEdit.value) {
      // 这里需要获取当前编辑的分类ID
      // 暂时使用模拟数据
      await categoryApi.updateCategory(editingId.value, form.value)
      ElMessage.success('分类更新成功')
    } else {
      await categoryApi.createCategory(form.value)
      ElMessage.success('分类创建成功')
    }

    dialogVisible.value = false
    fetchCategories()
    form.value = { name: '', slug: '', description: '' }
    isEdit.value = false
    editingId.value = null

  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('保存分类失败:', error)
      ElMessage.error('保存分类失败')
    }
  } finally {
    saving.value = false
  }
}

// 删除分类
const deleteCategory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await categoryApi.deleteCategory(id)
    ElMessage.success('删除成功')
    fetchCategories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
    }
  }
}

// 组件挂载
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped lang="scss">
.categories-page {
  background: #fafbfc;
  min-height: 100vh;
  padding: 32px 0;

  .search-section {
    margin-bottom: 24px;
  }
}

.categories-table {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #222;
}

.header-left {
  h2 {
    margin: 0 0 8px 0;
    font-size: 24px;
    color: #303133;
  }

  p {
    margin: 0;
    color: #909399;
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .categories-page {
    padding: 16px 0;
  }
  .categories-table {
    border-radius: 12px;
    padding: 12px;
  }
  .page-title {
    font-size: 18px;
  }
}
</style> 